<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      title="选择规则范围"
      width="60%"
      :before-close="handleClose"
      append-to-body
    >
      <!-- 城市多选组件 -->
      <el-card>
        <div slot="header">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            style="font-weight: bold"
            >全国</el-checkbox
          >
        </div>
        <div class="scrollbar">
          <el-scrollbar style="height: 100%">
            <el-card v-for="(item1, i1) in proCities" :key="i1">
              <div slot="header">
                <!-- 一级省份 -->
                <el-checkbox
                  style="font-weight: bold"
                  v-model="item1.selected"
                  :indeterminate="item1.isIndeterminate"
                  :label="item1.name"
                  @change="handleCheckedProChange($event, i1)"
                ></el-checkbox>
              </div>
              <div>
                <!-- 二级城市 -->
                <el-checkbox
                  v-for="(item2, i2) in item1.childs"
                  :key="i2"
                  v-model="item2.selected"
                  :label="item2.name"
                  @change="handleCheckedCityChange($event, i1, item2.code)"
                ></el-checkbox>
              </div>
            </el-card>
          </el-scrollbar>
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button class="theme-background-color" @click="saveRangeData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import regionData from '../../assets/js/regionChoose.js'

export default {
  props: {
    checkedRanges: {
      type: Array,
      default: function () {
        return {}
      }
    },
    cityVisible: {
      type: Boolean,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      visible: false,

      proCities: [],
      // 全选变量
      isIndeterminate: false,
      checkAll: '',
      checkedCities: []
    }
  },
  methods: {
    handleCheckAllChange(e) {
      //   选择所有下级
      var childrenArray = this.proCities
      this.checkLow(childrenArray, e)
      // 去掉半选
      this.isIndeterminate = false
    },
    handleCheckedProChange(e, index) {
      // console.log(e)
      // 一级勾选后，子级全部勾选或者取消
      this.proCities[index].selected = e
      //   去掉一级不确定状态
      this.proCities[index].isIndeterminate = false
      var childrenArray = this.proCities[index].childs

      this.checkLow(childrenArray, e)
      // console.log(this.proCities)
      //   全选框
      this.getIsCheckAll(this.proCities)
    },
    handleCheckedCityChange(e, firstIndex, secondCode) {
      // 处理一级框
      var higherArray = this.proCities[firstIndex]
      this.checkHigherCheckbox(higherArray, secondCode, e)
      //   全选框
      this.getIsCheckAll(this.proCities)
    },
    // 勾选下级
    checkLow(childrenArray, e) {
      if (childrenArray) {
        for (var i = 0, len = childrenArray.length; i < len; i++) {
          childrenArray[i].isIndeterminate = false
          childrenArray[i].selected = e
          if (childrenArray[i].childs) {
            this.checkLow(childrenArray[i].childs, e)
          }
        }
      }
    },
    getIsCheckAll(originData) {
      var tickCount = 0
      var unTickCount = 0
      var indeterminateCount = 0
      var ArrLength = originData.length
      for (var j = 0; j < ArrLength; j++) {
        // 全选checkbox状态
        if (originData[j].selected === true) tickCount++
        if (originData[j].selected === false) unTickCount++
        if (originData[j].isIndeterminate === true) indeterminateCount++
      }
      //   console.log(ArrLength)
      //   console.log(tickCount)
      //   console.log(unTickCount)
      //   console.log(indeterminateCount)
      if (tickCount === ArrLength) {
        // 全选勾选
        this.checkAll = true
        this.isIndeterminate = false
      } else if (unTickCount === ArrLength) {
        // 全选不勾选
        this.checkAll = false
        if (indeterminateCount > 0) {
          this.isIndeterminate = true
        } else {
          this.isIndeterminate = false
        }
      } else {
        this.checkAll = false
        // 添加全选不确定状态
        this.isIndeterminate = true
      }
    },
    // 根据当前级别级权限的选择状态，判断上级权限是否选中
    checkHigherCheckbox(higherArray, nowCode, e) {
      var childrenArray = higherArray.childs
      var tickCount = 0
      var unTickCount = 0
      var indeterminateCount = 0
      var len = childrenArray.length
      for (var i = 0; i < len; i++) {
        if (nowCode === childrenArray[i].code) childrenArray[i].selected = e
        if (childrenArray[i].selected === true) tickCount++
        if (childrenArray[i].selected === false) unTickCount++
        if (childrenArray[i].isIndeterminate === true) indeterminateCount++
      }
      // console.log('当前的ID：' + nowCode)
      // console.log('选中的：' + tickCount)
      // console.log('未选中的：' + unTickCount)
      // console.log('半选状态的：' + indeterminateCount)
      if (tickCount === len) {
        // 一级全勾选
        higherArray.selected = true
        higherArray.isIndeterminate = false
      } else if (unTickCount === len) {
        // 一级级全不勾选
        higherArray.selected = false
        if (indeterminateCount > 0) {
          higherArray.isIndeterminate = true
        } else {
          higherArray.isIndeterminate = false
        }
      } else {
        higherArray.selected = false
        // 添加一级不确定状态
        higherArray.isIndeterminate = true
      }
      // console.log('当前父节点：' + higherArray)
      // console.log('当前父节点的选中状态：' + higherArray.selected)
      // console.log('当前父节点的半选状态：' + higherArray.isIndeterminate)
    },
    // 循环树，找选中checkbox的值,城市
    checkedData() {
      const length = this.proCities.length
      var arr_name = []
      var arr_code = []
      for (var i = 0; i < length; i++) {
        if (
          this.proCities[i].selected === true ||
          this.proCities[i].isIndeterminate === true
        ) {
          const len = this.proCities[i].childs.length
          for (var j = 0; j < len; j++) {
            if (this.proCities[i].childs[j].selected === true) {
              arr_name.push(this.proCities[i].childs[j].name)
              arr_code.push(this.proCities[i].childs[j].code)
            }
          }
        }
      }
      return { name: arr_name, code: arr_code }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.$emit('update:cityVisible', false)
          done()
        })
        .catch((_) => {})
    },
    closeDialog() {
      this.$emit('update:cityVisible', false)
    },
    saveRangeData() {
      this.$emit('showCitiesData', this.checkedData())
      this.visible = false
      this.$emit('update:cityVisible', false)
    },
    defaultChecked() {
      this.isIndeterminate = false
      this.checkAll = false
      this.proCities = JSON.parse(JSON.stringify(regionData))
      this.checkedCities = this.checkedRanges
      // console.log(this.checkedCities)
      // console.log(this.proCities)
      // console.log(regionData)
      if (this.checkedCities.length === 0) return
      // 1、先选中城市
      var fa = 0
      var fahalf = 0
      for (let i = 0; i < this.proCities.length; i++) {
        var la = 0
        for (let j = 0; j < this.proCities[i].childs.length; j++) {
          if (
            this.checkedCities.indexOf(this.proCities[i].childs[j].code) !== -1
          ) {
            this.proCities[i].childs[j].selected = true
            la++
          } else {
            this.proCities[i].childs[j].selected = false
          }
        }
        // console.log('la：' + la)
        if (la === this.proCities[i].childs.length) {
          this.proCities[i].selected = true
          this.proCities[i].isIndeterminate = false
          fa++
        } else if (la > 0) {
          this.proCities[i].selected = false
          this.proCities[i].isIndeterminate = true
          fahalf++
        } else {
          this.proCities[i].selected = false
          this.proCities[i].isIndeterminate = false
        }
      }
      // console.log('fa:' + fa)
      // console.log('fahalf:' + fahalf)
      if (fa == this.proCities.length) {
        this.checkAll = true
        this.isIndeterminate = false
      } else if (fa === 0 && fahalf === 0) {
        this.checkAll = false
        this.isIndeterminate = false
      } else {
        this.checkAll = false
        this.isIndeterminate = true
      }
    }
  },
  // 默认值
  watch: {
    cityVisible() {
      this.visible = this.cityVisible
      if (this.visible) this.defaultChecked()
    }
    // checkedRanges: function () {
    //   this.defaultChecked()
    // }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  min-width: 112px;
  margin: 5px;
}
.scrollbar {
  height: 500px;
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
  }
  /deep/.is-horizontal {
    display: none;
  }
  /deep/ .el-card__header {
    padding: 10px 20px;
  }
  .el-card {
    min-width: 90%;
    margin-bottom: 10px;
  }
}
</style>
